package com.oocl.server.main;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.Socket;

import com.oocl.server.http.HttpRequest;
import com.oocl.server.http.HttpResponse;
import com.oocl.venus.utils.WebConfig;

public class ServerChater implements Runnable{
	private Socket socket;
	private String filePath;

	public ServerChater(Socket socket, String filePath) {
		super();
		this.socket = socket;
		this.filePath = filePath;
	}

	public void run() {
		System.out.println("-->Client connected.");
		HttpRequest request = new HttpRequest(socket);
		HttpResponse response = new HttpResponse(socket);

		try {
			String actionName = WebConfig.getAction(request.getPath());
			if (actionName != null) {
				Command command = (Command) Class.forName(actionName).newInstance();
				command.setRequest(request);
				command.setResponse(response);
				CommandInvoker commandInvoker = new CommandInvoker();
				commandInvoker.setCommand(command);
				commandInvoker.invoke();
			}
			if (request.getPath().endsWith("html")||request.getPath().endsWith("js")||request.getPath().endsWith("css")||request.getPath().endsWith("png")) {
				try {
					response.write(new FileInputStream(new File(filePath+"/"+request.getPath())));
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			}

		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		System.out.println("-->Client released.");
	}
}
